#!/usr/bin/sh
#
# fddist - file descriptor usage distributions.
#          Written using DTrace (Solaris 10 3/05).
#
# This prints distributions for read and write events by file descriptor,
# by process. This can be used to determine which file descriptor a 
# process is doing the most I/O with.
#
# $Id: fddist 3 2007-08-01 10:50:08Z brendan $
#
# USAGE:        fddist [-r|-w]      # hit Ctrl-C to end sample
#
# FIELDS:
#               EXEC       process name
#               PID        process ID
#               value      file descriptor
#               count      number of events
#
# BASED ON: /usr/demo/dtrace/lquantize.d
#
# SEE ALSO:
#           DTrace Guide "Aggregations" chapter (docs.sun.com)
#
# PORTIONS: Copyright (c) 2005, 2006 Brendan Gregg.
#
# CDDL HEADER START
#
#  The contents of this file are subject to the terms of the
#  Common Development and Distribution License, Version 1.0 only
#  (the "License").  You may not use this file except in compliance
#  with the License.
#
#  You can obtain a copy of the license at Docs/cddl1.txt
#  or http://www.opensolaris.org/os/licensing.
#  See the License for the specific language governing permissions
#  and limitations under the License.
#
# CDDL HEADER END
#
# 09-Jun-2005   Brendan Gregg   Created this.
# 20-Apr-2006	   "      "	Last update.


##############################
# --- Process Arguments ---
#

### Default variables
opt_read=0; opt_write=0

### Process options
while getopts hrw name
do
	case $name in
	r)      opt_read=1 ;;
	w)      opt_write=1 ;;
	h|?)    cat <<-END >&2
		USAGE: fddist [-r|-w] 
		              -r        # reads only
		              -w        # writes only
		  eg,
		       fddist           # default, r+w counts
		       fddist -r        # read count only
		END
		exit 1
	esac
done
shift `expr $OPTIND - 1`

### Option logic
if [ $opt_read -eq 0 -a $opt_write -eq 0 ]; then
	opt_read=1; opt_write=1
fi


#################################
# --- Main Program, DTrace ---
#
/usr/sbin/dtrace -n '
 #pragma D option quiet

 inline int OPT_read   = '$opt_read';
 inline int OPT_write  = '$opt_write';
 inline int FDMAX      = 255;

 /* print header */
 dtrace:::BEGIN
 {
	printf("Tracing ");
	OPT_read && OPT_write ? printf("reads and writes") : 1;
	OPT_read && ! OPT_write ? printf("reads") : 1;
	! OPT_read && OPT_write ? printf("writes") : 1;
	printf("... Hit Ctrl-C to end.\n");
 }

 /* sample reads */
 syscall::*read*:entry
 /OPT_read/
 {
	@Count[execname, pid] = lquantize(arg0, 0, FDMAX, 1);
 }

 /* sample writes */
 syscall::*write*:entry
 /OPT_write/
 {
	@Count[execname, pid] = lquantize(arg0, 0, FDMAX, 1);
 }

 /* print report */
 dtrace:::END
 {
	printa("EXEC: %-16s PID: %d\n%@d\n",@Count);
 }
'
